package com.example.exercise.common.mvc;

import com.example.exercise.common.base.BaseResponse;
import com.google.common.util.concurrent.RateLimiter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

/**
 * 限流拦截器
 */
@Component
public class RateLimitInterceptor implements HandlerInterceptor {
    //以每秒0.1次的速率生成令牌，方便测试用才设置这么小的哦
    RateLimiter rateLimiter = RateLimiter.create(0.1);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if(o instanceof ResourceHttpRequestHandler) {
            //资源拦截跳过
            return true;
        }
        //如果没有获取到令牌，说明令牌消耗过快，提示服务器繁忙
        if(!rateLimiter.tryAcquire()){
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpServletResponse.getOutputStream(), StandardCharsets.UTF_8);
            BaseResponse<String> baseResponse = new BaseResponse<>();
            baseResponse.errMsg("服务器繁忙");
            outputStreamWriter.write(baseResponse.toString());
            outputStreamWriter.flush();
            outputStreamWriter.close();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

    }
}
